package com.example.memento.download.web;

import com.example.memento.download.config.DownloadProperties;
import com.example.memento.download.service.DownloadService;
import com.example.memento.model.ApiResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(path = "/download", produces = MediaType.APPLICATION_JSON_VALUE)
public class DownloadController {
    private final DownloadService downloadService;
    private final DownloadProperties properties;

    public DownloadController(DownloadService downloadService, DownloadProperties properties) {
        this.downloadService = downloadService;
        this.properties = properties;
    }

    public static class DownloadRequest {
        @NotEmpty
        public List<String> urls;
        public String targetDir;
        public Boolean extract;
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public ApiResponse<Map<String, Object>> downloadAll(@Valid @RequestBody DownloadRequest req) throws IOException {
        Path dir = req.targetDir != null && !req.targetDir.isBlank() ? Path.of(req.targetDir) : Path.of(properties.getBaseDir());
        boolean doExtract = req.extract != null ? req.extract : properties.isExtract();
        var files = downloadService.downloadAll(req.urls, dir, doExtract);
        return ApiResponse.<Map<String, Object>>builder()
                .success(true)
                .message("OK")
                .data(Map.of(
                        "savedDir", dir.toAbsolutePath().toString(),
                        "files", files.stream().map(p -> p.toAbsolutePath().toString()).toList(),
                        "extract", doExtract
                ))
                .build();
    }
}


